import {Injectable, CanActivate, ExecutionContext } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { Observable } from "rxjs";

@Injectable()
export class RolesGuard implements CanActivate{
    constructor(private readonly reflector:Reflector){}

    canActivate(context:ExecutionContext,
    ):boolean | Promise<boolean> | Observable<boolean>{
        const request = context.switchToHttp().getRequest();
        const roles = this.reflector.get<string[]>('roles',context.getHandle());

        if(roles && roles.length){
            //需要校验用户权限
            //目前仅校验有无token字段，后续需要校验token正确性

            if(roles.some(item => 'user' == item))
             return(
                 request.query.token || request.body.token || request.headers.token
             );
        }

        return true;
    }

}